package com.miyuan.view.home;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.util.Log;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.miyuan.R;
import com.miyuan.base.BaseFragment;
import com.miyuan.view.replenish.ReplenishFinishActivity;


import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

import static android.content.Context.VIBRATOR_SERVICE;

public class ScanFragment extends BaseFragment implements QRCodeView.Delegate {
    QRCodeView mQRCodeView;

    private static final int REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY = 666;

    //构造函数
    public static ScanFragment newInstance() {
        ScanFragment scanFragment = new ScanFragment();
        scanFragment.setArguments(new Bundle());
        return scanFragment;
    }

    @Override
    public void onStart() {
        super.onStart();
        mQRCodeView.startCamera();
        mQRCodeView.startSpot();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFragmentLayout(R.layout.fragment_scan);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mQRCodeView = (ZXingView) getActivity().findViewById(R.id.zxingview);
        mQRCodeView.setDelegate(this);
        mQRCodeView.showScanRect();
    }

    @Override
    public void onStop() {
        mQRCodeView.stopCamera();
        super.onStop();
    }

    @Override
    public void onDestroy() {
        mQRCodeView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onResume() {
        mQRCodeView.showScanRect();
        mQRCodeView.startSpot();
        super.onResume();
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Bundle bundle = new Bundle();
        bundle.putString("QrResult", result);
        Intent intent = new Intent(getActivity(), ReplenishFinishActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Toast.makeText(getActivity(), "-->onScanQRCodeOpenCameraError", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mQRCodeView.showScanRect();
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY) {

        }
    }
}

